<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\validate;


use app\lib\exception\ParameterException;

class OrderPlace extends BaseValidate {
    
    // 父类自带验证规则变量，自动验证
    protected $rule = [
        'products' => 'checkProducts'
    ];

    // 自定义验证规则变量，需手动验证
    protected $singleRule = [
        'product_id' => 'require|isPositiveInteger',
        'count' => 'require|isPositiveInteger',
    ];

    /**
     * 验证产品数组参数
     * @param $values
     * @return bool
     * @throws ParameterException
     */
    protected function checkProducts($values)
    {
        if(!is_array($values))
        {
            throw new ParameterException([
                'msg' => '商品参数不正确',
            ]);
        }

        if(empty($values))
        {
            throw new ParameterException([
                'msg' => '商品列表不能为空',
            ]);
        }

        foreach($values as $value)
        {
            $this->checkProduct($value);
        }

        return true;
    }

    /**
     * 验证产品参数
     * @param $value
     * @throws ParameterException
     */
    protected function checkProduct($value)
    {
        $validate = new BaseValidate($this->singleRule);
        $result = $validate->check($value);
        if(!$result)
        {
            throw new ParameterException([
                'msg' => '商品列表参数错误',
            ]);
        }
    }
}